from flask import Blueprint, request, jsonify
from .models import db, Blog
from datetime import datetime

blog_bp = Blueprint('blog', __name__)

@blog_bp.route('/blogs', methods=['POST'])
def create_blog():
    data = request.get_json()
    if not data or 'title' not in data or 'content' not in data or 'author_id' not in data:
        return jsonify({'error': 'Missing required fields'}), 400

    new_blog = Blog(
        title=data['title'],
        content=data['content'],
        author_id=data['author_id'],
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow()
    )
    db.session.add(new_blog)
    db.session.commit()
    return jsonify({'message': 'Blog created successfully', 'id': new_blog.id}), 201

@blog_bp.route('/blogs/<int:blog_id>', methods=['PUT'])
def update_blog(blog_id):
    data = request.get_json()
    blog = Blog.query.get(blog_id)
    if not blog:
        return jsonify({'error': 'Blog not found'}), 404

    if 'title' in data:
        blog.title = data['title']
    if 'content' in data:
        blog.content = data['content']
    blog.updated_at = datetime.utcnow()
    db.session.commit()
    return jsonify({'message': 'Blog updated successfully'}), 200

@blog_bp.route('/blogs/<int:blog_id>', methods=['GET'])
def get_blog(blog_id):
    blog = Blog.query.get(blog_id)
    if not blog:
        return jsonify({'error': 'Blog not found'}), 404

    return jsonify({
        'id': blog.id,
        'title': blog.title,
        'content': blog.content,
        'author_id': blog.author_id,
        'created_at': blog.created_at,
        'updated_at': blog.updated_at
    }), 200